package com.ybg.engine.task;

import java.util.List;
import java.util.Map;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.ybg.engine.JobEngineFactory;
import com.ybg.util.DataSourceUtil;
import com.ybg.util.LogUtil;

/**
 * 定时遍历调度任务，去掉待停止任务并置为停止状态，添加带运行任务并置为运行状态
 * @author zhouqixin
 *
 */
@SuppressWarnings("deprecation")
@Repository
public class ControlJob implements StatefulJob{

	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		JdbcTemplate jdbcTemplate  = DataSourceUtil.beanFactory.getBean("jdbcTemplate", JdbcTemplate.class);
		traverseJobsWithOutCheck(jdbcTemplate);//遍历并处理所有的任务,-2停止，-1待停止，1待运行，2运行
	}
	
	/**
	 * 遍历并处理所有的任务,-2停止，-1待停止，1待运行，2运行
	 */
	public void traverseJobsWithOutCheck(JdbcTemplate jdbcTemplate){
		// 数据库中的调度任务
		List<Map<String, Object>> taskList = jdbcTemplate.queryForList("select * from task_definition");
		for (int i = 0; i < taskList.size(); i++) {
			if("1".equals(taskList.get(i).get("status"))){//把待运行状态置为运行状态并添加到调度任务列表
				jdbcTemplate.update("update task_definition set status=? where classname=?","2",
						taskList.get(i).get("classname"));
				try {
					JobEngineFactory.startJob((Class<? extends Task>)(Class.forName(
							taskList.get(i).get("classname")+"")), taskList.get(i).get("cronexpress") + "");
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					LogUtil.error("开启调度任务"+taskList.get(i).get("classname")+"失败", e);
				}
				
			}else if("-1".equals(taskList.get(i).get("status"))){//把待停止状态置为停止状态并停止任务
				jdbcTemplate.update("update task_definition set status=? where classname=?","-2",
						taskList.get(i).get("classname"));
				try {
					JobEngineFactory.stopJob((Class<? extends Task>)(Class.forName(
							taskList.get(i).get("classname")+"")));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					LogUtil.error("关闭调度任务"+taskList.get(i).get("classname")+"失败", e);
				}
				
			}
		}
					
	}
}
